<template>
  <div class="app-container">
    <!-- 顶部操作栏：仅保留“新增房型”按钮（右侧突出显示） -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="22" />
      <el-col :span="2">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:roomtype:add']"
        >新增房型</el-button>
      </el-col>
    </el-row>

    <!-- 房型表格 -->
    <el-table v-loading="loading" :data="roomtypeList" @selection-change="handleSelectionChange">
      <!-- 序号列 -->
      <el-table-column type="index" label="序号" align="center" width="60"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <!-- 房间图片列 -->
      <el-table-column label="房间图片" align="center" prop="roomImage" width="80">
        <template #default="scope">
          <img 
            :src="scope.row.roomImage" 
            :width="40" 
            :height="40" 
            style="object-fit: cover;" 
            v-if="scope.row.roomImage" 
          />
          <span v-else>无</span>
        </template>
      </el-table-column>
      <!-- 房间类型列 -->
      <el-table-column label="房间类型" align="center" prop="roomType" />
      <!-- 床位费用列（带单位） -->
      <el-table-column label="床位费用（元/月）" align="center" prop="bedFee" />
      <!-- 创建人列 -->
      <el-table-column label="创建人" align="center" prop="creator" />
      <!-- 房型介绍列 -->
      <el-table-column label="房型介绍" align="center" prop="roomDescription" width="180">
        <template #default="scope">
          <div class="room-description-cell">{{ scope.row.roomDescription }}</div>
        </template>
      </el-table-column>
      <!-- 创建时间列 -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
      <span>
  {{ 
    new Date(scope.row.createTime).getFullYear() + '-' + 
    (new Date(scope.row.createTime).getMonth() + 1).toString().padStart(2, '0') + '-' + 
    new Date(scope.row.createTime).getDate().toString().padStart(2, '0') + ' ' + 
    new Date(scope.row.createTime).getHours().toString().padStart(2, '0') + ':' + 
    new Date(scope.row.createTime).getMinutes().toString().padStart(2, '0') + ':' + 
    new Date(scope.row.createTime).getSeconds().toString().padStart(2, '0') 
  }}
</span>
        </template>
      </el-table-column>
      <!-- 状态列（标签化显示） -->
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 操作列（编辑、删除、启用/禁用） -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['system:roomtype:edit']"
          >编辑</el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['system:roomtype:remove']"
          >删除</el-button>
          <el-button 
            link 
            :type="scope.row.status === 1 ? 'danger' : 'success'" 
            @click="handleToggleStatus(scope.row)" 
            v-hasPermi="['system:roomtype:edit']"
          >{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑房型弹窗 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roomtypeRef" :model="form" :rules="rules" label-width="100px">
        <!-- 房型类型（必填、唯一、最多10字） -->
        <el-form-item label="房型类型" prop="roomType">
          <el-input 
            v-model="form.roomType" 
            placeholder="请输入房型类型（最多10字）" 
            maxlength="10" 
          />
        </el-form-item>
        <!-- 床位费用（必填、数字） -->
        <el-form-item label="床位费用" prop="bedFee">
          <el-input 
            v-model.number="form.bedFee" 
            placeholder="请输入床位费用" 
            type="number" 
          />
        </el-form-item>
        <!-- 状态（单选、默认启用） -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 房型图片（必填、格式/大小限制） -->
        <el-form-item label="房型图片" prop="roomImage">
          <el-upload
            class="upload-demo"
            action="#" 
            :on-success="handleImageSuccess"
            :file-list="fileList"
            :limit="1"
            accept=".png,.jpg,.jpeg"
            :before-upload="beforeImageUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
        <template #tip>
  <div class="el-upload__tip">图片大小不超过2M，仅支持PNG、JPG、JPEG格式</div>
      </template>
          </el-upload>
          <img 
            :src="form.roomImage" 
            :width="100" 
            :height="100" 
            v-if="form.roomImage" 
            style="margin-top: 10px;" 
          />
        </el-form-item>
        <!-- 房型介绍（必填、最多50字） -->
        <el-form-item label="房型介绍" prop="roomDescription">
          <el-input 
            v-model="form.roomDescription" 
            type="textarea" 
            placeholder="请输入房型介绍（最多50字）" 
            maxlength="50" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Roomtype">
import { listRoomtype, getRoomtype, delRoomtype, addRoomtype, updateRoomtype } from "@/api/bed/roomtype";
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance();

// 响应式数据
const roomtypeList = ref([]);
const open = ref(false);
const loading = ref(true);
const total = ref(0);
const title = ref("");
const fileList = ref([]); // 图片上传文件列表

const data = reactive({
  form: {
    id: null,
    roomType: null,
    bedFee: null,
    status: 1, // 默认启用
    roomImage: null,
    roomDescription: null,
    creator: null, // 实际可从登录态获取
    createTime: null,
    isDeleted: 0
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    roomType: [
      { required: true, message: "房型类型不能为空", trigger: "blur" },
      { max: 10, message: "房型类型最多10个字符", trigger: "blur" }
    ],
    bedFee: [
      { required: true, message: "床位费用不能为空", trigger: "blur" },
      { type: 'number', message: "床位费用必须为数字", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    roomImage: [
      { required: true, message: "房型图片不能为空", trigger: "change" }
    ],
    roomDescription: [
      { required: true, message: "房型介绍不能为空", trigger: "blur" },
      { max: 50, message: "房型介绍最多50个字符", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 查询房型列表
function getList() {
  loading.value = true;
  listRoomtype(queryParams.value).then(response => {
    roomtypeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消弹窗
function cancel() {
  open.value = false;
  reset();
  fileList.value = []; // 清空上传列表
}

// 重置表单
function reset() {
  form.value = {
    id: null,
    roomType: null,
    bedFee: null,
    status: 1, // 重置为默认启用
    roomImage: null,
    roomDescription: null,
    creator: null,
    createTime: null,
    isDeleted: 0
  };
  proxy.resetForm("roomtypeRef");
}

// 多选框选中（用于批量操作，保留权限兼容）
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增房型
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增房型";
  fileList.value = [];
}

// 编辑房型
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0];
  getRoomtype(_id).then(response => {
    form.value = response.data;
    title.value = "编辑房型";
    // 回显图片
    if (form.value.roomImage) {
      fileList.value = [{ url: form.value.roomImage }];
    } else {
      fileList.value = [];
    }
    open.value = true;
  });
}

// 提交表单（新增/编辑）
function submitForm() {
  proxy.$refs["roomtypeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRoomtype(form.value).then(() => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRoomtype(form.value).then(() => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除房型
function handleDelete(row) {
  const _ids = row.id || ids.value;
  const typeName = row.roomType || _ids;
  proxy.$modal.confirm(`是否确认删除房型“${typeName}”？`).then(() => {
    return delRoomtype(_ids);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
}
// 切换启用/禁用状态（修改后）
function handleToggleStatus(row) {
  const newStatus = row.status === 1 ? 0 : 1; // 1→0（禁用），0→1（启用）
  const tip = newStatus === 1 ? "启用" : "禁用";
  
  // 调用修改接口，仅传递 id 和 status
  proxy.$modal.confirm(`是否确认${tip}房型“${row.roomType}”？`).then(() => {
    return updateRoomtype({ 
      id: row.id,  // 房型ID
      status: newStatus  // 新状态
    });
  }).then(() => {
    getList(); // 刷新列表
    ElMessage.success(`${tip}成功`);
  }).catch(() => {});
}

// 图片上传成功回调（需替换为实际接口逻辑）
function handleImageSuccess(response, file) {
  // 假设接口返回图片地址在 response.data 中
  form.value.roomImage = response.data;
  fileList.value = [{ url: response.data }];
}

// 图片上传前校验
function beforeImageUpload(file) {
  const isImage = file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('仅支持上传PNG、JPG、JPEG格式的图片');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB');
    return false;
  }
  return true;
}

// 初始加载列表
getList();
</script>

<style lang="scss" scoped>
.room-description-cell {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5em;
  max-height: 3em; /* 2行的高度 */
  word-break: break-word;
}
</style>